<?php
/**
 * 京东裸扣的结果查询
 */
namespace App\Jobs;

use App\Constant\QueueKey;
use App\Events\CollectionReceiptEvent;
use App\Facades\RepayBuckleRequestFacade;
use App\Models\RepayRecord;
use App\Models\Traits\RepaySummary;
use EloquentFilter\TestClass\Client;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class RepayBuckleJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    /**
     * 任务最大尝试次数。
     *
     * @var int
     */
    public $tries = 5;

    /**
     * 任务运行的超时时间。
     *
     * @var int
     */
    public $timeout = 300; //秒数

    /**
     * @var RepayRecord
     */
    protected $record;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(RepayRecord $record)
    {
        $this->onQueue(QueueKey::QUEUE_REPAY_BUCKLE_RESULT);
        $this->record = $record;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $model = $this->record;
        $data = [
            'orderId' => $model->buckle_order_id
        ];
        $res = RepayBuckleRequestFacade::getBuckleMoneyResult($data);
        if($res['success'] == true){
            //请求到了京东裸扣那里
            //判断是否扣成功
            if($res['orderStatus'] == RepayRecord::ORDER_STATUS_SUCCESS){
                //todo 更改
                if(0 == $model->period){
                    //
                    \App\Models\RepaySummary::setAllPeriodSuccess($model);
                }else{
                    //
                    \App\Models\RepaySummary::setCurrentPeriodSuccess($model);
                }
            }else if($res['orderStatus'] == RepayRecord::ORDER_STATUS_FAIL){
                \App\Models\RepaySummary::failData($res,$model,$model->repay_type);
            }else if($res['orderStatus'] == RepayRecord::ORDER_STATUS_ING){
                return;
            }
            event(new CollectionReceiptEvent($model->id));
        }else{
            $res['errorMessage'] = '还款失败';
            //对方代码报错
            \App\Models\RepaySummary::failData($res,$model,$model->repay_type);
        }
        return ;
    }
}
